﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T.FAS.Runtime.MF.Runtime.Core
{
    internal class ConnectionStringConverter
    {
        public static string Convert(string source)
        {
            // 1. 解析原始连接字符串
            var sourceDict = ParseConnectionString(source);

            // 2. 建立键名映射关系
            var keyMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                ["server"] = "Server",
                ["database"] = "Database",
                ["user id"] = "Username",
                ["password"] = "Password",
                ["port"] = "Port"
            };

            // 3. 准备目标字典（带默认值）
            var targetDict = new Dictionary<string, string>
            {
                ["MaxPoolSize"] = "2000",   // 默认值
                ["Timeout"] = "60"          // 默认值
            };

            // 4. 执行转换映射
            foreach (var mapping in keyMappings)
            {
                if (sourceDict.TryGetValue(mapping.Key, out string value))
                {
                    targetDict[mapping.Value] = value;
                }
            }

            // 5. 特殊处理：原始字符串可能包含目标键名
            // 保持原始值优先级高于默认值
            foreach (var key in new[] { "MaxPoolSize", "Timeout" })
            {
                if (sourceDict.TryGetValue(key, out string value))
                {
                    targetDict[key] = value;
                }
            }

            // 6. 按目标格式生成新连接字符串
            return FormatConnectionString(targetDict);
        }

        private static Dictionary<string, string> ParseConnectionString(string connStr)
        {
            var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            var segments = connStr.Split(';', StringSplitOptions.RemoveEmptyEntries);

            foreach (var segment in segments)
            {
                int index = segment.IndexOf('=');
                if (index > 0)
                {
                    string key = segment.Substring(0, index).Trim();
                    string value = segment.Substring(index + 1).Trim();
                    dict[key] = value;
                }
            }
            return dict;
        }

        private static string FormatConnectionString(Dictionary<string, string> dict)
        {
            var sb = new StringBuilder();

            // 按目标格式要求的字段顺序
            var orderedKeys = new[] { "Server", "Username", "Database", "Port", "Password", "MaxPoolSize", "Timeout" };

            foreach (var key in orderedKeys)
            {
                if (dict.TryGetValue(key, out string value))
                {
                    if (sb.Length > 0) sb.Append(';');
                    sb.Append($"{key}={value}");
                }
            }

            return sb.ToString();
        }
    }
}
